<template style="width:100px;">
  <div v-loading="loading" class="gl_contentBox gl_heightFull">
    <div class="gl_mb_5 demo-input-suffix gl_searchBox">
      <el-row :gutter="20">
        <el-col :span="4">
          <p>名称搜索</p>
          <el-input v-model="getMsg.Name" placeholder="输入姓名查询" size="mini" clearable @change="getPageList()" />
        </el-col>
        <el-col :span="20" style="text-align:right">
          <el-button style="margin-top:27px" type="primary" size="mini" @click="getPageList()">查询</el-button>
          <el-button style="margin-top:27px" type="warning" size="mini" @click="resetData">重置</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="gl_margin_10 gl_clear">
      <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" @click="addExaminer">新增会员证书</el-button>
      <div style="display:inline-block;width:80px;height:28px;margin-right:10px;margin-left:10px;">
        <el-upload
          :action="action"
          :http-request="noticeUpload"
          :before-upload="beforeUpload"
          :auto-upload="true"
          :show-file-list="false"
          accept=".xlsx, .xls"
        >
          <el-button :loading="importLoading" type="primary" size="mini">导入数据</el-button>
        </el-upload>
      </div>
      <el-button style="margin-right:10px;" type="primary" :loading="buLoading" size="mini" @click="uploadFile()">导出Excel</el-button>
    </div>
    <el-table size="mini" :data="tableData" class="gl_table_noBorder mb_17 resetdate" style="width: 100%" :index="table_index">
      <el-table-column label="序号" type="index" align="center" width="46" />
      <el-table-column label="姓名" prop="name" />
      <el-table-column label="英文名" prop="englishName" width="70" />
      <el-table-column label="性别" prop="genderName" width="46" align="center" />
      <el-table-column label="证件类型" prop="idCardTypeCode" width="100">
        <template slot-scope="{ row }">
          <div class="select_padding">
            <el-select v-if="row.isEdit && row.idCardTypeCode !== 'IdCard'" v-model="row.inputIdCardTypeCode" style="width:100%" size="mini" placeholder="请选择">
              <el-option v-for="item in dict.idCardType" :key="item.code" :value="item.code" :label="item.value" />
            </el-select>
            <span v-else>{{ row.idCardTypeName }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="证件号" prop="idCardNumber" width="145">
        <template slot-scope="{ row }">
          <el-input v-if="row.isEdit && row.idCardTypeCode !== 'IdCard'" v-model="row.inputIdCardNumber" size="mini" />
          <span v-else>{{ row.idCardNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="日期" width="135" align="center">
        <template slot-scope="{ row }">
          <div class="date_padding">
            <span v-if="!row.isEdit">{{ row.passTheExamDateTime }}</span>
            <el-date-picker
              v-else
              v-model="row.inputPassTheExamDateTime"
              type="date"
              :prefix-icon="null"
              range-separator="至"
              placeholder="选择日期"
              style="width: 100%;"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              size="mini"
              :clearable="false"
              @change="handleTimeChange"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="地点" width="120">
        <template slot-scope="{ row }">
          <span v-if="!row.isEdit">{{ row.address }}</span>
          <el-input v-else v-model="row.inputAddress" size="mini" />
        </template>
      </el-table-column>
      <el-table-column label="证书类型" width="90">
        <template slot-scope="{ row }">
          <span v-if="!row.isEdit">{{ row.certificateTypeName }}</span>
          <el-input v-else v-model="row.inputCertificateTypeName" maxlength="50" size="mini" />
        </template>
      </el-table-column>
      <el-table-column label="证书名称" width="100">
        <template slot-scope="{ row }">
          <span v-if="!row.isEdit">{{ row.certificateName }}</span>
          <el-input v-else v-model="row.inputCertificateName" maxlength="50" size="mini" />
        </template>
      </el-table-column>
      <el-table-column label="证书编号" width="105">
        <template slot-scope="{ row }">
          <span v-if="!row.isEdit">{{ row.certificateNumber }}</span>
          <el-input v-else v-model="row.inputCertificateNumber" maxlength="50" size="mini" />
        </template>
      </el-table-column>
      <el-table-column label="证书等级" width="70">
        <template slot-scope="{ row }">
          <span v-if="!row.isEdit">{{ row.certificateLevel }}</span>
          <el-input v-else v-model="row.inputCertificateLevel" maxlength="20" size="mini" />
        </template>
      </el-table-column>
      <el-table-column label="证书有效期" width="130">
        <template slot-scope="{ row }">
          <div class="date_padding">
            <span v-if="!row.isEdit">{{ row.certificateEndDate }}</span>
            <el-date-picker
              v-else
              v-model="row.inputCertificateEndDate"
              type="date"
              range-separator="至"
              placeholder="选择日期"
              style="width: 100%;"
              :clearable="false"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              size="mini"
              @change="handleEndTimeChange"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="考官" width="80">
        <template slot-scope="{ row }">
          <span v-if="!row.isEdit">{{ row.examinerName }}</span>
          <el-input v-else v-model="row.inputExaminerName" size="mini" />
        </template>
      </el-table-column>
      <el-table-column label="考官编号" width="90">
        <template slot-scope="{ row }">
          <span v-if="!row.isEdit">{{ row.examinerNumber }}</span>
          <el-input v-else v-model="row.inputExaminerNumber" maxlength="8" size="mini" />
        </template>
      </el-table-column>
      <el-table-column label="培训师" width="80">
        <template slot-scope="{ row }">
          <span v-if="!row.isEdit">{{ row.trainerName }}</span>
          <el-input v-else v-model="row.inputTrainerName" size="mini" />
        </template>
      </el-table-column>
      <el-table-column label="培训师编号" width="90">
        <template slot-scope="{ row }">
          <span v-if="!row.isEdit">{{ row.trainerNumber }}</span>
          <el-input v-else v-model="row.inputTrainerNumber" maxlength="20" size="mini" />
        </template>
      </el-table-column>
      <el-table-column fixed="right" width="90" label="操作">
        <template slot-scope="{ row }">
          <el-button v-if="!row.isEdit" size="mini" type="text" @click="clickEidt(row)">编辑</el-button>
          <el-button v-if="!row.isEdit" size="mini" type="text" @click="clickDelete(row)"><span class="gl_color_error">删除</span></el-button>
          <el-button v-if="row.isEdit" size="mini" type="text" @click="clickConfirm(row)">完成</el-button>
          <el-button v-if="row.isEdit" size="mini" type="text" @click="clickCancel(row)"><span class="gl_color_error">取消</span></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-row style="text-align: right;">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="getMsg.MaxResultCount"
        :current-page="getMsg.Page"
        @size-change="changePageSize"
        @current-change="changePage"
      />
    </el-row>
    <add-certificate ref="addCertificate" :dict="dict" :dict-all="dictAll" />
  </div>
</template>

<script>
import { api_GET_DownLoadFileAddHeader } from '@/extend/api/file';
// import { api_POST_Excel } from '@/extend/api/trainswaggerApi/common';
import { SiSReportCreateExcelDto } from '@/lib/form/train/swaggerForm';
import { mapState, mapActions } from 'vuex';
import addCertificate from './addCertificate';
import { errorText } from '@/lib';
import axios from 'axios';
import {
  Api_GET_TrainCentreCertificateCentreCertificateQO, // 分页获取无锡中心证书
  SiSTKWTrainAddCentreCertificateInput,
  SiSTKWTrainUpdateCentreCertificateInput, // 修改
  Api_POST_TrainCentreCertificateImportVO // 导入会员
} from '@/lib/form/train/swaggerForm';
import {
  api_GET_TrainCentreCertificateCentreCertificate, // 分页获取无锡中心证书
  api_PUT_TrainCentreCertificateCentreCertificateId, // 证书修改
  api_DELETE_TrainCentreCertificateCentreCertificateId // 证书删除
  // api_POST_TrainCentreCertificateImport // 批量导入会员
} from '@/extend/api/trainswaggerApi/app';
export default {
  components: {
    addCertificate
  },
  data () {
    return {
      getMsg: new Api_GET_TrainCentreCertificateCentreCertificateQO(),
      selectedMsg: new SiSTKWTrainAddCentreCertificateInput(),
      updateMsg: new SiSTKWTrainUpdateCentreCertificateInput(),
      importMsg: new Api_POST_TrainCentreCertificateImportVO(),
      loading: false,
      tableData: [],
      action: `${process.env.VUE_APP_API_SWAGGER_TRAIN}/api/app/train/CentreCertificate/import`,
      exportMsg: new SiSReportCreateExcelDto(),
      total: 0,
      importLoading: false,
      buLoading: false
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict,
      dictAll: state => state.dict.dictAll
    })
  },
  created () {
    this.getDictByType(['district']);
    this.getDict();
    this.getPageList();
  },
  methods: {
    init() {
      this.$refs.entryNoticeUpload.init();
    },
    ...mapActions({ getDictByType: 'dict/getDictByType', getDict: 'dict/getDict' }),
    // 分页获取证书列表
    getPageList (page) {
      this.loading = true;
      this.getMsg.Page = page || 1;
      this.getMsg.SkipCount = (this.getMsg.Page - 1) * this.getMsg.MaxResultCount;
      api_GET_TrainCentreCertificateCentreCertificate(this.getMsg).then(res => {
        this.loading = false;
        this.total = res.totalCount;
        this.tableData = res.items;
        if (res && res.items.length > 0) {
          this.tableData = res.items.map(item => {
            item.passTheExamDateTime = item.passTheExamDateTime ? item.passTheExamDateTime.split('T')[0] : item.passTheExamDateTime;
            item.certificateEndDate = item.certificateEndDate ? item.certificateEndDate.split('T')[0] : item.certificateEndDate;
            this.$set(item, 'isEdit', false);
            return item;
          });
        }
      }, error => {
        this.loading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 删除证书
    clickDelete (row) {
      const that = this;
      this.$confirm(`您确定要删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          that.loading = true;
          api_DELETE_TrainCentreCertificateCentreCertificateId(row.id).then(res => {
            if (res) {
              that.loading = false;
              this.getPageList();
              this.$message({ type: 'success', message: '删除成功' });
            }
          }, error => {
            that.loading = false;
            const _msg = error.error.message || error.message;
            this.$message({ type: 'error', message: _msg });
          });
        })
        .catch(() => {
        });
    },
    // 编辑单条信息
    clickEidt (row) {
      row.isEdit = true;
      this.$set(row, 'inputAddress', row.address);
      this.$set(row, 'inputExaminerName', row.examinerName);
      this.$set(row, 'inputIdCardTypeCode', row.idCardTypeCode);
      this.$set(row, 'inputIdCardNumber', row.idCardNumber);
      this.$set(row, 'inputExaminerNumber', row.examinerNumber);
      this.$set(row, 'inputTrainerName', row.trainerName);
      this.$set(row, 'inputTrainerNumber', row.trainerNumber);
      this.$set(row, 'inputCertificateTypeName', row.certificateTypeName);
      this.$set(row, 'inputCertificateName', row.certificateName);
      this.$set(row, 'inputCertificateNumber', row.certificateNumber);
      this.$set(row, 'inputCertificateLevel', row.certificateLevel);
      this.$set(row, 'inputPassTheExamDateTime', row.passTheExamDateTime);
      this.updateMsg.passTheExamDateTime = row.passTheExamDateTime;
      this.$set(row, 'inputCertificateEndDate', row.certificateEndDate);
      this.updateMsg.certificateEndDate = row.certificateEndDate;
    },
    // 确认单条信息
    clickConfirm (row) {
      const that = this;
      let prompt = '';
      prompt = row.inputIdCardTypeCode ? prompt : (prompt + '证件类型');
      prompt = row.inputIdCardNumber ? prompt : (prompt + '证件号');
      prompt = row.inputAddress ? prompt : (prompt + ' 地点');
      prompt = row.inputPassTheExamDateTime ? prompt : (prompt + ' 日期');
      prompt = row.inputCertificateTypeName ? prompt : (prompt + ' 证书类型');
      prompt = row.inputCertificateName ? prompt : (prompt + ' 证书名称');
      prompt = row.inputCertificateNumber ? prompt : (prompt + ' 证书编号');
      prompt = row.inputCertificateLevel ? prompt : (prompt + ' 证书等级');
      if (prompt !== '') {
        prompt = prompt + '不能为空';
        this.$message({ type: 'warning', message: prompt });
        return;
      }
      const idNumber = /^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}([0-9]|x|X)$/;
      if (row.inputIdCardTypeCode === 'IdCard' && !idNumber.test(row.inputIdCardNumber)) {
        this.$message({ type: 'warning', message: '身份证号格式错误' });
        return;
      }
      if (row.inputExaminerNumber !== '' && !/^[A-Za-z0-9]{1,8}$/.test(row.inputExaminerNumber)) {
        this.$message({ type: 'warning', message: '考官编号格式错误' });
        return;
      }
      if (!/^[A-Za-z0-9]{1,50}$/.test(row.inputCertificateNumber)) {
        this.$message({ type: 'warning', message: '证书编号格式错误' });
        return;
      }
      if (row.inputTrainerNumber !== '' && !/^[A-Za-z0-9]{1,50}$/.test(row.inputTrainerNumber)) {
        this.$message({ type: 'warning', message: '培训师编号格式错误' });
        return;
      }
      this.$set(this.updateMsg, 'idCardTypeCode', row.inputIdCardTypeCode);
      this.updateMsg.idCardNumber = row.inputIdCardNumber;
      this.updateMsg.address = row.inputAddress;
      this.updateMsg.examinerName = row.inputExaminerName;
      this.updateMsg.examinerNumber = row.inputExaminerNumber;
      this.updateMsg.certificateTypeName = row.inputCertificateTypeName;
      this.updateMsg.certificateLevel = row.inputCertificateLevel;
      this.updateMsg.certificateNumber = row.inputCertificateNumber;
      this.updateMsg.certificateName = row.inputCertificateName;
      this.updateMsg.trainerName = row.inputTrainerName;
      this.updateMsg.trainerNumber = row.inputTrainerNumber;
      this.dict.idCardType.forEach(item => {
        if (item.code === that.updateMsg.idCardTypeCode) {
          that.$set(that.updateMsg, 'idCardTypeName', item.value);
        }
      });
      api_PUT_TrainCentreCertificateCentreCertificateId(row.id, this.updateMsg).then(res => {
        row.isEdit = false;
        if (res) {
          this.getPageList();
          this.$message({ type: 'success', message: '修改成功' });
        }
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 取消单条信息
    clickCancel (row) {
      row.isEdit = false;
    },
    // 重置列表
    resetData() {
      this.$set(this.getMsg, 'Name', '');
      this.getPageList();
    },
    // 添加证书按钮
    addExaminer(row, type) {
      this.$refs.addCertificate.open(row, type);
    },
    cancelDialog() {
    },
    // reportData() {
    //   this.exportMsg.reportName = 'CentreCertificates';
    //   if (this.getMsg.Name === null) {
    //     this.getMsg.Name = '';
    //   }
    //   this.$set(this.exportMsg.parameters, 'Name', this.getMsg.Name);
    //   api_POST_Excel(this.exportMsg)
    //     .then(res => {
    //       if (res) {
    //         this.uploadFile(this.getMsg.Name);
    //       }
    //     })
    //     .catch(error => {
    //       const _msg = error.error.message || error.message;
    //       this.$message({ type: 'error', message: _msg });
    //     });
    // },
    // 导出Excel
    uploadFile() {
      var that = this;
      this.buLoading = true;
      if (this.getMsg.Name === null) {
        this.getMsg.Name = '';
      }
      const tempUrl = `/api/excel`;
      const fileName = '会员证书' + '.xlsx';
      const params = {
        Name: this.getMsg.Name,
        ReportName: 'CentreCertificates'
      };
      const code = WEB_CONFIG.VUE_APP_SWAGGER_TRAIN_BASE;
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, params, code).then(res => {
        that.buLoading = false;
      }).catch(error => {
        that.buLoading = false;
        errorText(error).then(function(text) {
          that.$message({ type: 'error', message: text });
        });
      });
    },
    // 上传文件限制
    check(file) {
      const isJPG =
        file.type ===
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.type === 'application/vnd.ms-excel';
      if (!isJPG) {
        this.$message.error('上传文件只能是 .xls或者.xlsx 格式!');
      }
      return isJPG;
    },
    // 上传前拦截
    beforeUpload(file) {
      const isCheck = this.check(file);
      if (isCheck) {
        this.files = file;
      } else {
        this.files = '';
      }
    },
    // 导入
    noticeUpload() {
      return new Promise((resolve, reject) => {
        if (!this.files) reject(new Error());
        var that = this;
        if (this.files) {
          that.importLoading = true;
          const form = new FormData();
          form.append('formFile', this.files);
          this.uploadApi(this.action, form)
            .then(res => {
              that.$message({ type: 'success', message: '导入成功' });
              that.getPageList();
              that.importLoading = false;
            })
            .catch(error => {
              that.importLoading = false;
              that.$message({
                type: 'error',
                message: '导入失败 ' + error.error && error.error.message
              });
            });
        }
      });
    },
    // 上传图片的api
    uploadApi(url, file) {
      const config = {
        headers: {
          Authorization: 'Bearer ' + this.$store.state.user.token
        }
      };
      return axios.post(url, file, config);
    },
    handleTimeChange(time) {
      this.updateMsg.passTheExamDateTime = time;
    },
    handleEndTimeChange(time) {
      this.$set(this.updateMsg, 'certificateEndDate', time);
    },
    // 分页
    changePage(page) {
      this.getPageList(page);
    },
    changePageSize(pagesize) {
      this.getMsg.MaxResultCount = pagesize;
      this.getPageList();
    },
    // 序号递增
    table_index(index) {
      return (this.getMsg.Page - 1) * this.getMsg.MaxResultCount + index + 1;
    }
  }
};
</script>

<style lang="scss" scoped>
  .mb_17 {
    margin-bottom: 17px;
  }
  .timeTitle {
    display: inline-block;
    height: 18px;
    font-size: 14px;
    line-height: 18px;
    font-family: PingFang SC, PingFang SC-Regular;
    font-weight: 500;
  }
  .timeMessageCol {
    color: #ff4949;
  }
  .queryResult {
    width: 100%;
    border: 1px solid rgba(0,0,0,0.15);
    border-radius: 4px;
  }
  .hg_30 {
    height: 32px;
  }
  .hg_22 {
    height: 22px;
  }
</style>
<style>
.date_padding .el-input--suffix .el-input__inner {
  padding-left: 30px;
}
.select_padding .el-input--suffix .el-input__inner {
  padding-right: 30px;
}
.resetdate .el-input__inner {
  padding: 0 5px;
}
</style>
